﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Specifies that a client-side element ID or element is assigned to a variable.
	/// </summary>
	public class AssignedClientId : BaseClientId, IAssignedClientId
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public AssignedClientId()
		{
			this.Variable = "";
			this.Resolve = AssignedClientIdResolveMode.Control;
		}
		#endregion
		#region PROPS
		/// <summary>
		/// The variable to be assigned.
		/// </summary>
		[DefaultValue("")]
		public string Variable
		{
			get
			{
				if (string.IsNullOrEmpty(this._variable))
					return this.ControlId;
				return this._variable;
			}
			set
			{
				this._variable = value;
			}
		}
		/// <summary>
		/// Gets or sets a flag which indicates whether the element ID will be resolved into an element.
		/// </summary>
		[DefaultValue(AssignedClientIdResolveMode.Control)]
		public AssignedClientIdResolveMode Resolve { get; set; }
		#endregion
		#region METHODS
		/// <summary>
		/// Gets the client script used to initialize this client ID reference.
		/// </summary>
		/// <returns></returns>
		public override string GetScript()
		{
			if (this.Control.Visible)
			{
				switch (this.Resolve)
				{
					case AssignedClientIdResolveMode.None:
						return string.Format("{0} = \"{1}\";", this.GetVariableName(), this.Control.ClientID);
					case AssignedClientIdResolveMode.Element:
						return string.Format("{0} = $(\"{1}\");", this.GetVariableName(), this.Control.ClientID);
					case AssignedClientIdResolveMode.Control:
						return string.Format("{0} = $(\"{1}\").get_Object();", this.GetVariableName(), this.Control.ClientID);
				}
			}
			return null;
		}
		#endregion
		#endregion
		#region INTERNAL
		#region VARS
		string _variable;
		#endregion
		#region METHODS
		/// <summary>
		/// Returns the complete variable name to which the ID or the element needs to be assigned.
		/// </summary>
		/// <returns></returns>
		protected string GetVariableName()
		{
			Manager m = this.Parent as Manager;
			if (m != null)
				return m.ClientScriptVariablePrefix + this.Variable;
			return this.Variable;
		}
		#endregion
		#endregion
	}
}
